class Product < ActiveRecord::Base
  has_many :variations, :as => :variable, :dependent => :destroy
  belongs_to :category
  has_and_belongs_to_many :tax_treatments
  has_one :sku, :as => :stockable, :dependent => :destroy
  validates_presence_of :name
  validates_presence_of :description
  validates_presence_of :price
  
  def file=(incoming_file) 
    @temp_file = incoming_file
    #manually set the ActiveRecord field since its the file that is posted (and not filename)
    self.filename = incoming_file.original_filename 
    #@content_type = incoming_file.content_type
  end
  
  def after_save 
    if @temp_file
      save_file = "#{RAILS_ROOT}/public/images/products/#{self.filename}"
      logger.debug("saving " + save_file)
      @temp_file.rewind      
      File.open(save_file, "wb") do |f|
        f.write(@temp_file.read)
      end
    end
  end
  
  # if product has a new category then we may need to delete variations associated with the  
  # previous category
  def before_update
    return if self.category.nil?
    unless self.category.variations.empty? 
      self.ar_variations.each do |v|
        v.destroy
      end
    end
    ar_tax_treatments.clear unless self.category.tax_treatments.empty? 
  end
  
  def apply_tax_treatment?(id)
    return true if self.tax_treatments.any? {|tt| tt.id == id} 
    return self.category.tax_treatments.any? {|tt| tt.id == id} unless self.category.nil?
  end
  
  # Serious Ruby hacking going on here.  We alias the original method for the association as added by 
  # ActiveRecord and then override it so we can return the categories variations if they are present.
  alias :ar_variations :variations
  def variations
    v = ar_variations
    return v unless v.empty?
    return v if self.category.nil?
    if self.category.variations.empty?
      # return the products variations
      return v
    else
      # return a frozen copy of the cateogires variations
      return Array.new(self.category.variations).freeze   
    end
  end   
  
  # Serious Ruby hacking going on here.  We alias the original method for the association as added by 
  # ActiveRecord and then override it so we can return the categories treatments if they are present.
  alias :ar_tax_treatments :tax_treatments
  def tax_treatments
    tt = ar_tax_treatments
    return tt unless tt.empty?
    return tt if self.category.nil?
    if self.category.tax_treatments.empty?
      # return empty array (does not need to be frozen since category has none)
      return tt
    else
      # return a frozen copy of the cateogires variations
      return Array.new(self.category.tax_treatments).freeze   
    end
  end  
end